<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <el-card class="search-card" v-show="showSearch">
            <el-form :model="queryParams">
                <el-row :gutter="20">
                    <el-col :span="7">
                        <el-form-item label="模型名称">
                            <el-input v-model="queryParams.templateName" placeholder="请输入模型名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="所属系统">
                            <el-select v-model="queryParams.applicationId" placeholder="请选择">
                                <el-option :label="item.name" :value="item.id" v-for="item in siteTypeAppSelect"
                                    :key="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item>
                            <el-button type="primary" @click="handleQuery">查询</el-button>
                            <el-button @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 操作按钮区域 -->
        <el-card class="operation-card">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="Plus" @click="showAddDialog"
                        v-hasPermi="['system:user:add']">新增</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="danger" plain icon="Delete" :disabled="!selectedIds.length"
                        @click="handleBatchDelete" v-hasPermi="['system:user:remove']">删除</el-button>
                </el-col>
                <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
            </el-row>
            <el-table v-loading="loading" :data="templateList" style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column type="index" label="序号" width="55" align="center" />
                <!-- <el-table-column prop="siteTemplateId" label="模型ID" align="center" width="100" /> -->
                <el-table-column prop="templateName" label="模型名称" align="center" />
                <el-table-column prop="basicSiteInfo" label="基本站点信息" align="center" />
                <!-- <el-table-column prop="associatedSystems" label="关联系统" align="center" /> -->
                <el-table-column prop="associatedSystems" align="center" label="关联系统">
                    <template #default="scope">
                        <el-tag>{{siteTypeAppSelect.find((item) => item.id ==
                            scope.row.associatedSystems)?.name}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="creator" label="创建人" align="center" />
                <el-table-column prop="createTime" label="创建时间" align="center" width="180">
                    <template #default="{ row }">
                        {{ formatTime(row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="lastUpdateTime" label="更新时间" align="center" width="180">
                    <template #default="{ row }">
                        {{ formatTime(row.lastUpdateTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="180" fixed="right">
                    <template #default="{ row }">
                        <el-button type="text" icon="Edit" @click="showEditDialog(row)">编辑</el-button>
                        <el-button type="text" icon="Delete" @click="handleDelete(row.siteTemplateId)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
                    :total="total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleQuery" @current-change="handleQuery" />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="50%" @closed="resetForm">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="模型ID" prop="siteTemplateId" v-if="dialog.isEdit">
                    <el-input v-model="form.siteTemplateId" disabled />
                </el-form-item>

                <el-form-item label="模型名称" prop="templateName">
                    <el-input v-model="form.templateName" placeholder="请输入模型名称" />
                </el-form-item>

                <el-form-item label="基本站点信息" prop="basicSiteInfo">
                    <el-input v-model="form.basicSiteInfo" type="textarea" :rows="3" placeholder="请输入基本站点信息" />
                </el-form-item>

                <el-form-item label="关联系统" prop="associatedSystems">
                    <el-select v-model="form.associatedSystems" placeholder="请选择">
                        <el-option :label="item.name" :value="item.id + ''" v-for="item in siteTypeAppSelect"
                            :key="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="自定义属性" prop="customProperties">
                    <el-input v-model="form.customProperties" type="textarea" :rows="3" placeholder="请输入自定义属性" />
                </el-form-item>

                <el-form-item label="属性扩展模式" prop="propertyExtensionSchema">
                    <el-input v-model="form.propertyExtensionSchema" type="textarea" :rows="3"
                        placeholder="请输入属性扩展模式" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="dialog.visible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import {
    getSiteTemplateList,
    getSiteTemplateDetail,
    addSiteTemplate,
    updateSiteTemplate,
    deleteSiteTemplate,
    getBasicSiteTemplateAppSelect
} from '@/api/basic/site/basicSiteTemplate.js'

const showSearch = ref(true);
// 数据状态
const loading = ref(false)
const templateList = ref([])
const total = ref(0)
const selectedIds = ref([])
const formRef = ref(null)
const siteTypeAppSelect = ref([])
// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    templateName: '',
    applicationId: ''
})

// 表单数据
const form = reactive({
    siteTemplateId: null,
    templateName: '',
    basicSiteInfo: '',
    associatedSystems: '',
    customProperties: '',
    propertyExtensionSchema: '',
    remark: '',
    isDeleted: 0
})

// 对话框状态
const dialog = reactive({
    visible: false,
    title: '新增站点模型',
    isEdit: false
})

// 表单验证规则
const rules = reactive({
    templateName: [
        { required: true, message: '请输入模型名称', trigger: 'blur' },
        { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
    ],
    associatedSystems: [
        { required: true, message: '请输入关联系统ID', trigger: 'blur' }
    ]
})

// 获取站点模型列表
const getList = async () => {
    loading.value = true
    try {
        const res = await getSiteTemplateList(queryParams)
        templateList.value = res?.rows || []
        total.value = res?.total || 0
    } catch (error) {
        console.error('获取站点模型列表失败:', error)
        ElMessage.error('获取站点模型列表失败')
    } finally {
        loading.value = false
    }
}

// 查询处理
const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
}

// 重置查询
const resetQuery = () => {
    queryParams.pageNum = 1
    queryParams.templateName = ''
    queryParams.applicationId = ''
    getList()
}

// 多选处理
const handleSelectionChange = (selection) => {
    selectedIds.value = selection.map(item => item.siteTemplateId)
}

// 显示新增对话框
const showAddDialog = () => {
    dialog.visible = true
    dialog.title = '新增站点模型'
    dialog.isEdit = false
    resetForm()
}

// 显示编辑对话框
const showEditDialog = async (row) => {
    try {
        const res = await getSiteTemplateDetail(row.siteTemplateId)
        Object.assign(form, res.data)
        dialog.visible = true
        dialog.title = '编辑站点模型'
        dialog.isEdit = true
    } catch {
        console.error('获取详情失败:', error)
        ElMessage.error('获取详情失败')
    }
}

// 删除站点模型
const handleDelete = async (id) => {
    try {
        await ElMessageBox.confirm('确认删除该站点模型吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        await deleteSiteTemplate(id)
        ElMessage.success('删除成功')
        getList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }
}

// 批量删除
const handleBatchDelete = async () => {
    if (selectedIds.value.length === 0) {
        ElMessage.warning('请至少选择一条记录')
        return
    }

    try {
        await ElMessageBox.confirm(`确认删除选中的${selectedIds.value.length}条记录吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        await deleteSiteTemplate(selectedIds.value.join(','))
        ElMessage.success('批量删除成功')
        getList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量删除失败:', error)
            ElMessage.error('批量删除失败')
        }
    }
}

// 重置表单
const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
    Object.assign(form, {
        siteTemplateId: null,
        templateName: '',
        basicSiteInfo: '',
        associatedSystems: '',
        customProperties: '',
        propertyExtensionSchema: '',
        remark: '',
        isDeleted: 0
    })
}

// 提交表单
const submitForm = async () => {
    try {
        await formRef.value.validate()

        if (dialog.isEdit) {
            await updateSiteTemplate(form)
            ElMessage.success('修改成功')
        } else {
            await addSiteTemplate(form)
            ElMessage.success('新增成功')
        }

        dialog.visible = false
        getList()
    } catch (error) {
        if (error && error.fields) {
            ElMessage.warning('请检查表单填写是否正确')
        } else {
            console.error('操作失败:', error)
            ElMessage.error('操作失败')
        }
    }
}

// 格式化时间
const formatTime = (time) => {
    if (!time) return ''
    return new Date(time).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    }).replace(/\//g, '-')
}

getBasicSiteTemplateAppSelect().then((response) => {
    siteTypeAppSelect.value = response.data;
})
// 初始化
getList()
</script>

<style scoped>
.el-card :deep(.el-form-item) {
    margin-bottom: 0px;
}

.app-container {
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.operation-card {
    margin-bottom: 20px;
}

.operation-buttons {
    display: flex;
    gap: 10px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}
</style>